package org.finesys.samples.netty.websocket.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.stomp.DefaultStompFrame;
import io.netty.handler.codec.stomp.StompCommand;
import io.netty.handler.codec.stomp.StompFrame;
import org.finesys.common.netty.websocket.support.NettyChannelMap;
import org.finesys.common.netty.websocket.support.NettySession;

public class StompClientHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Connected to server");
        StompFrame frame = new DefaultStompFrame(StompCommand.CONNECT);
        frame.content().writeBytes("accept-version:1.2,1.1,1.0\nheart-beat:10000".getBytes());
        ctx.writeAndFlush(frame);
        //
        NettySession nettySession = new NettySession(ctx.channel());
        NettyChannelMap.getInstance().put(ctx.channel().id().asShortText(), nettySession);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Received message: " + msg);
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        String body = new String(bytes, "UTF-8");
        System.out.println("Server response: " + body);


    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Read complete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("Exception caught: " + cause.getMessage());
        ctx.close();
    }
}
